package cn.tedu.order.service;

import cn.tedu.cart.api.CartApi;
import cn.tedu.order.mapper.OrderMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.pojo.Cart2;
import com.jt.common.pojo.Order;
import com.jt.common.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderService {
    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired
    private CartApi cartApi;

    @Autowired
    private RestTemplate restTemplate;
    //private static final ObjectMapper mapper=new ObjectMapper();

    public void addOrder(Order order) {
        //删除购物车
        String userId = order.getUserId();
        try {
            List<Cart2> carts = cartApi.queryMyCarts(userId);
            //String urlQuery = "http://cart-service/cart/manage/query?userId="+userId;
            //List<Cart2> carts = (List<Cart2>) restTemplate.getForObject(urlQuery, Cart2.class);
            //ResponseEntity<Cart> cart = restTemplate.exchange(urlQuery, HttpMethod.GET, null, Cart.class);
            //Cart cart =  restTemplate.getForObject(urlQuery, Cart.class);
            for (Cart2 cart : carts) {
                String urlDelete = "http://cart-service/cart/manage/delete?productId={1}&userId={2}";
                restTemplate.getForObject(urlDelete,Cart2.class,cart.getProductId(),userId);
                //cartApi.deleteCart(cart);
            }
            //String orderDelete = mapper.writeValueAsString(cart);
            //String productId = cart.getProductId();
            //Cart body = cart.getBody();
            //String urlDelete = "http://cart-service/cart/manage/delete?product={1}&userId={2}";
            //restTemplate.getForObject(urlDelete,Cart.class,productId,userId);
        } catch (Exception e) {
            e.printStackTrace();
        }


        order.setOrderId(UUID.randomUUID().toString());
        order.setOrderTime(new Date());
        order.setOrderPaystate(0);
        orderMapper.insertOrder(order);
    }

    public List<Order> queryMyOrders(String userId) {
        return orderMapper.selectOrdersByUserid(userId);
    }

    public void deleteOrder(String orderId) {
        orderMapper.deleteOrder(orderId);
    }
}
